var winston = require('winston');
var Promise = require('bluebird');

var myQuery = function(connection, queryString){
	return new Promise(function(resolve, reject){
		connection.query(queryString, function(err, rows){
			if(err){
				reject(err);
			}else{
				resolve(rows);
			}
		});
	});
}

module.exports = function(pool, req, res, next){
	var eventId = req.params.eventId;
	
	if(eventId){
		var queryPhotos = 'SELECT COUNT(*) FROM photo_list WHERE event_id=' + eventId;
		var queryPrints = 'SELECT SUM(copies) FROM print_list WHERE event_id=' + eventId;
		var queryShares = 'SELECT * FROM share_access WHERE event_id=' + eventId;
		var queryEmails = 'SELECT * FROM email_sent WHERE event_id=' + eventId;
		pool.getConnection(function(err, connection){
			if(err){
				winston.error('DB connection error: ' + err);
				res.status(500).send('DB connection error: ' + err);
			}else{
				Promise.join(myQuery(connection, queryPhotos), myQuery(connection, queryPrints), myQuery(connection, queryShares), myQuery(connection, queryEmails))
					.then(function(args){
						var jsonObj = {};
						jsonObj.photoTotal = args[0][0]["COUNT(*)"];
						jsonObj.printTotal = args[1][0]["SUM(copies)"];
						jsonObj.shares = args[2];
						jsonObj.emails = args[3];
						res.send(jsonObj);
						connection.release();
					}).catch(function(err){
						winston.error(err);
						res.send(err);
						connection.release();
					});
			}
		});
	}else{
		winston.error('ROUT error, can not get eventId');
		res.status(500).send('ROUT error, can not get eventId')
	}
	
}